package cn.usian.service.impl;

import cn.usian.fegin.CarFeign;
import cn.usian.jyzx.model.entity.h5.CartInfo;
import cn.usian.jyzx.model.entity.order.OrderItem;
import cn.usian.jyzx.model.vo.common.Result;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import cn.usian.jyzx.model.vo.h5.TradeVo;
import cn.usian.mapper.OrderMapper;
import cn.usian.service.OrderService;
import cn.util.AuthThreadLocalUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceimpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    CarFeign carFeign;

    @Override
    public Result<TradeVo> trade() {
        Long id = AuthThreadLocalUtils.get().getId();
        List<Object> values = redisTemplate.boundHashOps("cart"+id).values();
        List<CartInfo> cartInfoList = values.stream().map(value -> JSON.parseObject(value.toString(), CartInfo.class))
                .collect(Collectors.toList());

//        Result<List<CartInfo>> listResult = carFeign.cartList();
//        List<CartInfo> resultData = listResult.getData();

        ArrayList<OrderItem> orderItems = new ArrayList<>();
        BigDecimal bigDecimal=new BigDecimal(0);
        for (CartInfo cartInfo : cartInfoList) {
            bigDecimal=bigDecimal.add(cartInfo.getCartPrice().multiply(BigDecimal.valueOf(cartInfo.getSkuNum())));
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo,orderItem);
            orderItem.setThumbImg(cartInfo.getImgUrl());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
//            orderItem.setOrderId(cartInfo.getSkuId());
            orderItems.add(orderItem);
        }
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItems);
        tradeVo.setTotalAmount(bigDecimal);
        return Result.build(tradeVo, ResultCodeEnum.SUCCESS);
    }
}
